package com.ibeetl.springboot.ch3.controller;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.servlet.ModelAndView;

import com.ibeetl.springboot.ch3.entity.User;
import com.ibeetl.springboot.ch3.service.UserService;

@Controller
@RequestMapping("/async")
public class AsyncController {
	@Autowired UserService userService;
	
	BlockingQueue queue =  new LinkedBlockingQueue(20)  ;
	
	ThreadPoolExecutor tp = new ThreadPoolExecutor(1,10,60,TimeUnit.MINUTES,queue);
	
	@GetMapping("/showuser.html")
	public  Callable<ModelAndView> showUserInfo(Long id){
		Callable<ModelAndView> call = new Callable<ModelAndView>() {
			@Override
			public ModelAndView call() throws Exception {
				ModelAndView view = new ModelAndView();
				User user = userService.getUserById(id);
				view.addObject("user",user);
				view.setViewName("/userInfo");
				return view;
			}
		};
		return call;
	}
	
	@GetMapping("/showuser2.html")
	public  DeferredResult<ModelAndView> showUserInfo2(Long id){
		DeferredResult<ModelAndView>  result = new DeferredResult<ModelAndView> ();
		//放入自定义的tp线程池
		tp.execute(new Runnable() {
			
			@Override
			public void run() {
				ModelAndView view = new ModelAndView();
				User user = userService.getUserById(id);
				view.addObject("user",user);
				view.setViewName("/userInfo");
				//setResult 方法内部会将view对象放入Spring MVC中再次渲染输出
				result.setResult(view);
			}
			
		});
		return result;
	}
}
